﻿using Common;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Channels;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HK
{
    public class Helper
    {
        private Int32 m_lDownHandle = -1;

        [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 96, ArraySubType = UnmanagedType.U4)]
        private int[] iChannelNum;

        private long iSelIndex = 0;

        private Int32 m_lUserID = -1;

        private uint iLastErr = 0;

        string str;

        DateTime startTime= DateTime.Now.AddMinutes(-2);
        DateTime endTime= DateTime.Now.AddMinutes(-1);

        public CHCNetSDK.NET_DVR_DEVICEINFO_V30 DeviceInfo;
        public  void Start(string ip,int port,string uName,string pwd)
        {
            CHCNetSDK.NET_DVR_Init();
            //登录设备 Login the device
            m_lUserID = CHCNetSDK.NET_DVR_Login_V30(ip, port, uName, pwd, ref DeviceInfo);
            if (m_lUserID < 0)
            {
                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                str = "NET_DVR_Login_V30 failed, error code= " + iLastErr; //登录失败，输出错误号
                MessageBox.Show(str);
                return;
            }
            else
            {
                ////登录成功
                //MessageBox.Show("Login Success!");
                //btnLogin.Text = "Logout";

                //dwAChanTotalNum = (uint)DeviceInfo.byChanNum;
                //dwDChanTotalNum = (uint)DeviceInfo.byIPChanNum + 256 * (uint)DeviceInfo.byHighDChanNum;

                //if (dwDChanTotalNum > 0)
                //{
                //    InfoIPChannel();
                //}
                //else
                //{
                //    for (i = 0; i < dwAChanTotalNum; i++)
                //    {
                //        ListAnalogChannel(i + 1, 1);
                //        iChannelNum[i] = i + (int)DeviceInfo.byStartChan;
                //    }
                //    // MessageBox.Show("This device has no IP channel!");
                //}
            }




            if (m_lDownHandle >= 0)
            {
                MessageBox.Show("Downloading, please stop firstly!");//正在下载，请先停止下载
                return;
            }

            CHCNetSDK.NET_DVR_PLAYCOND struDownPara = new CHCNetSDK.NET_DVR_PLAYCOND();
            struDownPara.dwChannel = 33; //通道号 Channel number  

            //设置下载的开始时间 Set the starting time
            struDownPara.struStartTime.dwYear = (uint)startTime.Year;
            struDownPara.struStartTime.dwMonth = (uint)startTime.Month;
            struDownPara.struStartTime.dwDay = (uint)startTime.Day;
            struDownPara.struStartTime.dwHour = (uint)startTime.Hour;
            struDownPara.struStartTime.dwMinute = (uint)startTime.Minute;
            struDownPara.struStartTime.dwSecond = (uint)startTime.Second;

            //设置下载的结束时间 Set the stopping time
            struDownPara.struStopTime.dwYear = (uint)endTime.Year;
            struDownPara.struStopTime.dwMonth = (uint)endTime.Month;
            struDownPara.struStopTime.dwDay = (uint)endTime.Day;
            struDownPara.struStopTime.dwHour = (uint)endTime.Hour;
            struDownPara.struStopTime.dwMinute = (uint)endTime.Minute;
            struDownPara.struStopTime.dwSecond = (uint)endTime.Second;

            string sVideoFileName;  //录像文件保存路径和文件名 the path and file name to save      
            sVideoFileName = "D:\\Downtest_Channel" + struDownPara.dwChannel + ".mp4";


            DateTime? time = DVR_GetTimeInfo(m_lUserID);

            //按时间下载 Download by time
            m_lDownHandle = CHCNetSDK.NET_DVR_GetFileByTime_V40(m_lUserID, sVideoFileName, ref struDownPara);
            if (m_lDownHandle < 0)
            {
                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                str = "NET_DVR_GetFileByTime_V40 failed, error code= " + iLastErr;
                MessageBox.Show(str);
                return;
            }

            uint iOutValue = 0;
            if (!CHCNetSDK.NET_DVR_PlayBackControl_V40(m_lDownHandle, CHCNetSDK.NET_DVR_PLAYSTART, IntPtr.Zero, 0, IntPtr.Zero, ref iOutValue))
            {
                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                str = "NET_DVR_PLAYSTART failed, error code= " + iLastErr; //下载控制失败，输出错误号
                MessageBox.Show(str);
                return;
            }
            Pross();
        }
        int m_lRealHandle1 = -1;

        public void StartZP(string ip, int port, string uName, string pwd,PictureBox pictureBox1)
        {
            CHCNetSDK.NET_DVR_Init();
            //登录设备 Login the device
           var userid=  m_lUserID = CHCNetSDK.NET_DVR_Login_V30(ip, port, uName, pwd, ref DeviceInfo);
            if (m_lUserID < 0)
            {
                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                str = "NET_DVR_Login_V30 failed, error code= " + iLastErr; //登录失败，输出错误号
                MessageBox.Show(str);
                return;
            }
            else
            {
                ////登录成功
                //MessageBox.Show("Login Success!");
            }
            CHCNetSDK.NET_DVR_DEVICEINFO_V30 nET_DVR_DEVICEINFO_V = DeviceInfo;


            int ichannel = 33;
            int dwStreamType = 0;
            //if (nET_DVR_DEVICEINFO_V.byIPChanNum > 0)
            //{
            //    ichannel = nET_DVR_DEVICEINFO_V.byStartDChan + ichannel - 1;
            //}

            //强制I帧 Make a I frame
            CHCNetSDK.NET_DVR_PREVIEWINFO lpPreviewInfo = new CHCNetSDK.NET_DVR_PREVIEWINFO();
            lpPreviewInfo.hPlayWnd = pictureBox1.Handle;//预览窗口
            lpPreviewInfo.lChannel = ichannel;//预te览的设备通道
            lpPreviewInfo.dwStreamType = (uint)dwStreamType;//码流类型：0-主码流，1-子码流，2-码流3，3-码流4，以此类推
            lpPreviewInfo.dwLinkMode = 0;//连接方式：0- TCP方式，1- UDP方式，2- 多播方式，3- RTP方式，4-RTP/RTSP，5-RSTP/HTTP 
            lpPreviewInfo.bBlocked = false; //0- 非阻塞取流，1- 阻塞取流

            IntPtr pUser = new IntPtr();
            var  m_lRealHandle = CHCNetSDK.NET_DVR_RealPlay_V40(userid, ref lpPreviewInfo, null/*RealData*/, pUser);

            m_lRealHandle1 = m_lRealHandle;
            CHCNetSDK.NET_DVR_MakeKeyFrame(userid, ichannel);

            string path = "D:\\Downtest_Channel" + 11 + ".h264";
            //开始录像 Start recording
            if (!CHCNetSDK.NET_DVR_SaveRealData(m_lRealHandle, path))
            {
                uint iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                //string errorMsg = CacheManager.Instance.GetNVRErrorMsg((int)iLastErr);
                //string smessage = string.Format("录像设备启动失败(开始录像) 通道号：{0} 号牌号码:{1} 检验项目:{2} 错误代码:{3}", jysp.tdh, jysp.hphm, jysp.jyxm, errorMsg);
                //NetLogHelper.WriteLog(LogLevel.Error, MethodInfo.GetCurrentMethod().Name, smessage);
                //停止预览
                CHCNetSDK.NET_DVR_StopRealPlay(m_lRealHandle);
                m_lRealHandle = -1;
            }
            else
            {
                //m_bRecord = true;
                //result = true;
            }
            //CHCNetSDK.NET_DVR_SaveRealData(m_lRealHandle, path);

            //string text = DVR_GetTimeInfo(m_lUserID);
            //if (!text.Equals(""))
            //{
            //    DateTime now = DateTime.Now;
            //    DateTime d = DateTime.ParseExact(text, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
            //    if (Math.Abs((d - now).TotalMilliseconds) >= 2000.0)
            //    {
            //        DVR_SetTimeInfo(userid);
            //    }
            //}
        }
        public void StopZP()
        {
            CHCNetSDK.NET_DVR_StopRealPlay(m_lRealHandle1);
            m_lRealHandle1 = -1;
        }
        void Pross()
        {
            int iPos = 0;
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    Thread.Sleep(100);

                    //获取下载进度
                    iPos = CHCNetSDK.NET_DVR_GetDownloadPos(m_lDownHandle);

                    //if ((iPos > DownloadProgressBar.Minimum) && (iPos < DownloadProgressBar.Maximum))
                    //{
                    //    DownloadProgressBar.Value = iPos;
                    //}

                    if (iPos == 100)  //下载完成
                    {
                        //DownloadProgressBar.Value = iPos;
                        if (!CHCNetSDK.NET_DVR_StopGetFile(m_lDownHandle))
                        {
                            iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                            str = "NET_DVR_StopGetFile failed, error code= " + iLastErr; //下载控制失败，输出错误号
                            MessageBox.Show(str);
                            return;
                        }
                        m_lDownHandle = -1;
                        MessageBox.Show("下载完成");
                        //timerDownload.Stop();
                    }

                    if (iPos == 200) //网络异常，下载失败
                    {
                        MessageBox.Show("The downloading is abnormal for the abnormal network!");
                        //timerDownload.Stop();
                    }
                }
            });
        }
        public DateTime? DVR_GetTimeInfo(int lUserID)
        {
            DateTime? nvrTime = null;
            CHCNetSDK.NET_DVR_TIME nET_DVR_TIME = default(CHCNetSDK.NET_DVR_TIME);
            int num = Marshal.SizeOf(nET_DVR_TIME);
            IntPtr intPtr = Marshal.AllocCoTaskMem(num);
            Marshal.StructureToPtr(nET_DVR_TIME, intPtr, false);
            uint dwReturn = 0;
            bool flag = CHCNetSDK.NET_DVR_GetDVRConfig(lUserID, CHCNetSDK.NET_DVR_GET_TIMECFG, -1, intPtr, (uint)num, ref dwReturn);
            if (flag)
            {
                nET_DVR_TIME = (CHCNetSDK.NET_DVR_TIME)Marshal.PtrToStructure(intPtr, typeof(CHCNetSDK.NET_DVR_TIME));
                string timeStr = string.Format("{0:D4}-{1:D2}-{2:D2} {3:D2}:{4:D2}:{5:D2}.000", new object[]{
            nET_DVR_TIME.dwYear,
            nET_DVR_TIME.dwMonth,
            nET_DVR_TIME.dwDay,
            nET_DVR_TIME.dwHour,
            nET_DVR_TIME.dwMinute,
            nET_DVR_TIME.dwSecond
                });
                nvrTime = DateTime.ParseExact(timeStr, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
            }
            Marshal.FreeCoTaskMem(intPtr);
            return nvrTime;
        }
        //public 
    }
}
